package icu.wdtt.StpInterface;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import icu.wdtt.model.Role;
import icu.wdtt.model.User;
import icu.wdtt.service.UserService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限认证类
 */
@Component
public class StpInterfaceImpl  implements StpInterface {
    @Autowired
    private UserService userService;

    /*
    返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object o, String s) {
        if(!StpUtil.isLogin()) {
            throw new NotLoginException(null, null, null);
        }
        User user = userService.getUserAndRoleByUid(StpUtil.getLoginIdAsInt());

        List<Role> roleList = user.getRoleList();

        List<String> list = new ArrayList<>();

        for (Role role : roleList) {
            role.getAuthorityList().forEach(authority -> {list.add(authority.getPermissionCode());});
        }
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合
     * @param o
     * @param s
     * @return
     */
    @Override
    public List<String> getRoleList(Object o, String s) {
        if(!StpUtil.isLogin()){
            throw new NotLoginException(null,null,null);
        }
        List<String> list = new ArrayList<>();
        userService.getUserAndRoleByUid(StpUtil.getLoginIdAsInt()).getRoleList().forEach(role -> {list.add(role.getRname());});
        return list;
    }
}
